<template>
    <el-card v-loading="loading">
        <template #header>
            <div class="card-header">
                <div class="buttons">
                    <div class="mb-4">
                        <el-button type="primary" round @click="addNew">新增</el-button>
                        <el-button type="success" round @click="update">修改</el-button>
                        <el-button type="danger" round @click="handeleDelete">删除</el-button>
                        <el-button type="warning" round @click="toggleSelection()">清空选择</el-button>
                    </div>
                </div>
            </div>
        </template>
        <el-table ref="multipleTableRef" :data="tableData" :tree-props="treeProps" row-key="id"
            @selection-change="handleSelectionChange" @row-click="handleRowChick">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="name" label="菜单标题" />
            <el-table-column prop="type" label="类型" />
            <el-table-column prop="path" label="组件路径" />
        </el-table>

        <!-- 更新菜单表单 -->
        <el-drawer v-model="drawer_update" title="修改员工">
            <el-form ref="updateFormRef" style="max-width: 600px" :model="updateForm" :rules="updaterules"
                label-width="auto" class="demo-ruleForm" status-icon>
                <el-form-item label="类型" prop="type">
                    <el-radio-group v-model="updateForm.type">
                        <el-radio-button value="目录">目录</el-radio-button>
                        <el-radio-button value="菜单">菜单</el-radio-button>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="名称" prop="name">
                    <el-input v-model="updateForm.name" />
                </el-form-item>
                <el-form-item label="组件地址" prop="path">
                    <el-input v-model="updateForm.path" />
                </el-form-item>


                <el-form-item>
                    <el-button type="primary" @click="submitUpdateForm(updateFormRef)">
                        提交
                    </el-button>
                    <el-button @click="resetUpdateForm(updateFormRef)">重置表单</el-button>
                </el-form-item>
            </el-form>
        </el-drawer>

        <!-- 新建菜单表单 -->
        <el-drawer v-model="drawer_new" title="新建员工">
            <el-form ref="newFormRef" style="max-width: 600px" :model="newForm" :rules="newrules" label-width="auto"
                class="demo-ruleForm" status-icon>
                <el-form-item label="类型" prop="type">
                    <el-radio-group v-model="newForm.type">
                        <el-radio-button value="目录">目录</el-radio-button>
                        <el-radio-button value="菜单">菜单</el-radio-button>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="名称" prop="name">
                    <el-input v-model="newForm.name" />
                </el-form-item>
                <el-form-item label="组件地址" prop="path">
                    <el-input v-model="newForm.path" />
                </el-form-item>

                <el-form-item v-if="newForm.type == '菜单'" label="上级目录" prop="parent">
                    <el-select v-model="newForm.parent" placeholder="">
                        <el-option v-for="(item) in tableData" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>



                <el-form-item>
                    <el-button type="primary" @click="submitNewForm(newFormRef)">
                        提交
                    </el-button>
                    <el-button @click="resetNewForm(newFormRef)">重置表单</el-button>
                </el-form-item>
            </el-form>
        </el-drawer>



    </el-card>
</template>


<script lang="ts" setup>
import { reactive, ref, onBeforeMount } from 'vue'
import { ElTable, ElTree, ElNotification } from 'element-plus'
import { getMenu, createMenu, deleteMenu, updateMenu } from '@/api/menu';
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'

interface Menu {
    id: string
    path: string
    name: string
    children?: Array<object>
    parent?: string
    type: string
}
const drawer_new = ref(false)
const drawer_update = ref(false)

const loading = ref(false)
const treeProps = reactive({
    checkStrictly: true,
    children: 'children',
    label: 'label',
})

const tableData: Menu[] = reactive([

])

const addNew = () => {
    drawer_new.value = true
}

const update = () => {
    if (multipleSelection.value.length != 1) {
        ElNotification({
            title: "Warning",
            message: "请选择单个选项",
            type: "warning"
        })
    } else {
        drawer_update.value = true;
    }
}

const handeleDelete = () => {

}

const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref<Menu[]>([])
const toggleSelection = (rows?: Menu[]) => {
    if (rows) {
        rows.forEach((row) => {
            multipleTableRef.value!.toggleRowSelection(row, undefined)
        })
    } else {
        multipleTableRef.value!.clearSelection()
    }

}

const handleRowChick = (row) => {
    const selected = multipleSelection.value.some((item) => item.id === row.id)
    if (!selected) {
        multipleSelection.value.push(row)
        multipleTableRef.value.toggleRowSelection(row, true)
    } else {
        const finArr = multipleSelection.value.filter((item) => {
            return item.id !== row.id
        })
        multipleSelection.value = finArr
        multipleTableRef.value.toggleRowSelection(row, false)
    }

}

const handleSelectionChange = (val: Menu[]) => {
    multipleSelection.value = val
}

const getAllMenu = async () => {
    loading.value = true
    tableData.length = 0;
    const res = await getMenu()
    if (res != null) {
        if (res.status == "200") {
            // ElNotification({
            //     title: "Success",
            //     type: "success",
            //     message: "成功"
            // })
            console.log("获取成功============>", res)
            const { data } = res
            for (let i of data) {
                if (i.children != null) {
                    let tempc = {
                        id: i.id,
                        name: i.meta.title,
                        path: i.component,
                        type: "目录",
                        children: []
                    }
                    for (let j of i.children) {
                        tempc.children.push({
                            id: j.id,
                            name: j.meta.title,
                            path: j.component,
                            type: "菜单"
                        })
                    }
                    tableData.push(tempc)
                } else {
                    tableData.push({
                        id: i.id,
                        name: i.name,
                        path: i.component,
                        type: "目录"
                    })
                }
                console.log(tableData)
            }
        } else {
            console.log("获取失败", res.status)
        }
    } else {
        console.log("请求失败")
    }
    loading.value = false
}

const newFormRef = ref<FormInstance>()
const newForm = reactive<Menu>({
    id: '',
    name: '',
    path: '',
    type: '目录'

})

const updateFormRef = ref<FormInstance>()
const updateForm = reactive<Menu>({
    id: '',
    name: '',
    path: '',
    type: '目录'

})

const newrules = reactive<FormRules<Menu>>({
    name: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '长度应在3到20个字符之间', trigger: 'blur' },
    ],
})

const updaterules = reactive<FormRules<Menu>>({
    name: [
        { min: 3, max: 20, message: '长度应在3到20个字符之间', trigger: 'blur' },
    ],
})

const submitUpdateForm = async (formEl: FormInstance | undefined) => {
    // if (!formEl) return
    // await formEl.validate(async (valid, fields) => {
    //     if (valid) {
    //         loading.value = true
    //         updateForm.id = multipleSelection.value[0].id
    //         updateForm.name = updateForm.name || multipleSelection.value[0].name
    //         updateForm.level = updateForm.level || multipleSelection.value[0].level
    //         updateForm.dataScope = updateForm.dataScope || multipleSelection.value[0].dataScope
    //         updateForm.menus = multipleSelection.value[0].menus
    //         updateForm.createTime = multipleSelection.value[0].createTime
    //         const res = await updateRole(updateForm);
    //         if (res.status == '204') {
    //             ElNotification({
    //                 title: 'Success',
    //                 message: "修改成功",
    //                 type: 'success'
    //             })
    //             tableData[tableData.findIndex(x => x.id == updateForm.id)] = { ...updateForm }
    //             drawer_update.value = false
    //         }
    //     } else {
    //         console.log('error submit!', fields)
    //     }
    //     loading.value = false
    // })
}

const resetUpdateForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

const submitNewForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            loading.value = true
            let temp = {}
            if (newForm.type == '目录') {
                temp = {
                    title: newForm.name,
                    component: '',
                    iframe: false,
                    path:'',
                    type:0,
                }
            } else {
                temp = {
                    title: newForm.name,
                    component: newForm.path,
                    pid: newForm.parent,
                    iframe: false,
                    path:'',
                    type:1,
                }
            }
            const res = await createMenu(temp);
            if (res.status == '201') {
                ElNotification({
                    title: "Success",
                    type: "success",
                    message: "添加成功"
                })
                drawer_new.value = false
                getAllMenu()
            } else {
                ElNotification({
                    type: "error",
                    title: "Error",
                    message: '添加失败' + res.data.message
                })
                loading.value = false
            }
        }
        else {
            console.log('error submit!', fields)
            loading.value = false
        }
    })
}

const resetNewForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

onBeforeMount(() => {
    getAllMenu()
})
</script>